<template>
  <div class="counter-container">
    <!-- 数量 -1 按钮 -->
    <button type="button" class="btn btn-light btn-sm" @click="reduceCount">
      -
    </button>
    <!-- 输入框 -->
    <input
      type="number"
      class="form-control form-control-sm ipt-num"
      v-model.number="num"
    />
    <!-- 数量 +1 按钮 -->
    <button type="button" class="btn btn-light btn-sm" @click="addCount">
      +
    </button>
  </div>
</template>

<script>
import bus from '../../eventBus.js'
export default {
  name: 'EsCounter',
  emits: ['changCount'],
  props: {
    count: {
      type: Number,
      default: 0
    },
    minCount: {
      type: Number,
      default: 1
    },
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      num: this.count
    }
  },
  methods: {
    addCount() {
      this.num++
    },
    reduceCount() {
      if (this.num <= 0) return
      this.num--
    }
  },
  watch: {
    num(newVal) {
      if (this.num <= 0) return
      else bus.emit('changCount', { id: this.id, value: newVal })
    }
  }
}
</script>

<style lang="less" scoped>
.counter-container {
  display: flex;
  // 按钮的样式
  .btn {
    width: 25px;
  }
  // 输入框的样式
  .ipt-num {
    width: 34px;
    text-align: center;
    margin: 0 4px;
  }
}
</style>
